from core.util import timer_elapse
import setting as c
import requests
from core.log import logger

class MhxyQAOcrFacade(object):
    
    def mhxyQA_ocr(self, id, file_path, token):
        with open(file_path, 'rb') as f:
            files = {'image': ("", f, 'image/jpeg')}  # 根据您的图片格式调整 'image/jpeg'
            url = f"{c.URL_QA_OCR()}?id={id}&token={token}&version={c.VERSION}"
            
            text = ""
            res = []
            ocrleftcount = 0
            message = ""
            annc_server = ""
            annc_sponsor = ""
            ok = False
            try:
                response = requests.post(url, files=files, verify=False, timeout=c.REQUEST_TIMEOUT)
            except requests.exceptions.Timeout:
                logger.info("ocr 请求超时")
                return None, ok
            
            if response.status_code == 200:
                word_result = response.json()
                logger.info(word_result)
                if "word_result" in word_result:
                    text = word_result["text"]
                    res = word_result["word_result"]
                    ocrleftcount = word_result["ocrleftcount"]
                    message = word_result["message"]
                    annc_server = word_result["annc_server"]
                    annc_sponsor = word_result["annc_sponsor"]
                    logger.info(f"上传成功，响应：{response.status_code} {res}")
                    ok = True
            else:
                logger.info(f"上传失败，错误代码：{response.status_code} {file_path}")
            
            return (text, res, ocrleftcount, message, annc_server, annc_sponsor), ok
        
        
    @timer_elapse
    def recognize(self, id, img, token):
        logger.info(img)
        res, ok = self.mhxyQA_ocr(id, img, token)
        return res, ok
    
    @timer_elapse
    def search(self, id, kw):
        url = f"{c.URL_QA_SEARCH()}?id={id}&kw={kw}&version={c.VERSION}"
        logger.info(url)
        res = []
        annc_server = ""
        annc_sponsor = ""
        ok = False
        try:
            response = requests.get(url, verify=False, timeout=c.REQUEST_TIMEOUT)
        except requests.exceptions.Timeout:
            logger.info("search 请求超时")
            return None, False
        
        if response.status_code == 200:
            word_result = response.json()
            logger.info(word_result)
            if "word_result" in word_result:
                res = word_result["word_result"]
                annc_server = word_result["annc_server"]
                annc_sponsor = word_result["annc_sponsor"]
                ok = True
        return (res, annc_server, annc_sponsor), ok
    
    @timer_elapse
    def signup(self, username, email, password,  invitated):
        data = {
            'username': username,
            'password': password,
            'email': email,
            'invitated': invitated,
        }
        try:
            response = requests.post(c.URL_QA_SIGNUP(), json=data, verify=False, timeout=c.REQUEST_TIMEOUT)
        except requests.exceptions.Timeout:
            logger.info("signup 请求超时")
            return "", False
        
        # 检查响应
        if response.status_code == 200:
            # logger.info("上传成功！")
            # logger.info("响应内容：", response.text)
            return response.text, True
        else:
            logger.info("上传失败，状态码：", response.status_code)
            return "", False
        
    @timer_elapse
    def signin(self, email, password):
        data = {
            'password': password,
            'email': email,
        }
        try:
            response = requests.post(c.URL_QA_SIGNIN(), json=data, verify=False, timeout=c.REQUEST_TIMEOUT)
        except requests.exceptions.Timeout:
            logger.info("signin 请求超时")
            return "", False
        
        # 检查响应
        if response.status_code == 200:
            # logger.info("上传成功！")
            # logger.info("响应内容：", response.text)
            return response.text, True
        else:
            logger.info("上传失败，状态码：", response.status_code)
            return "", False
        
    @timer_elapse
    def subscribe_detect(self, file_path, kw1, kw2, kw3, token):
        with open(file_path, 'rb') as f:
            files = {'image': ("", f, 'image/jpeg')}  # 根据您的图片格式调整 'image/jpeg'
            url = f"{c.URL_QA_SUBSCRIBE()}?token={token}&version={c.VERSION}"
            if kw1 != "":
                url = f"{url}&kw1={kw1}"
                
            if kw2 != "":
                url = f"{url}&kw2={kw2}"
                
            if kw3 != "":
                url = f"{url}&kw3={kw3}"
                
            kw = ""
            sr = -1
            leftcount = 0
            message = ""
            ok = False
            try:
                response = requests.post(url, files=files, verify=False, timeout=c.REQUEST_TIMEOUT_LONG)
            except requests.exceptions.Timeout:
                logger.info("ocr 请求超时")
                return None, ok
            
            if response.status_code == 200:
                word_result = response.json()
                logger.info(word_result)
                if "subscribe_result" in word_result:
                    kw = word_result["kw"]
                    sr = word_result["subscribe_result"]
                    leftcount = word_result["ocrleftcount"]
                    message = word_result["message"]
                    left = word_result["left"]
                    top = word_result["top"]
                    right = word_result["right"]
                    bottom = word_result["bottom"]
                    logger.info(f"上传成功，响应：{response.status_code} {sr}")
                    ok = True
            else:
                logger.info(f"上传失败，错误代码：{response.status_code} {file_path}")
            
            return (kw, sr, leftcount, message, left, top, right, bottom), ok
        
    def mhxy_coord_ocr(self, file_path, token):
        with open(file_path, 'rb') as f:
            files = {'image': ("", f, 'image/jpeg')}  # 根据您的图片格式调整 'image/jpeg'
            url = f"{c.URL_QA_COORD()}?token={token}&version={c.VERSION}"
            
            coord = ""
            ocrleftcount = 0
            message = ""
            annc_server = ""
            annc_sponsor = ""
            ok = False
            try:
                response = requests.post(url, files=files, verify=False, timeout=c.REQUEST_TIMEOUT)
            except requests.exceptions.Timeout:
                logger.info("ocr 请求超时")
                return None, ok
            
            if response.status_code == 200:
                word_result = response.json()
                logger.info(word_result)
                if "coord_result" in word_result:
                    coord = word_result["coord_result"]
                    ocrleftcount = word_result["ocrleftcount"]
                    message = word_result["message"]
                    annc_server = word_result["annc_server"]
                    annc_sponsor = word_result["annc_sponsor"]
                    logger.info(f"上传成功，响应：{response.status_code} {coord}")
                    ok = True
            else:
                logger.info(f"上传失败，错误代码：{response.status_code} {file_path}")
            
            return (coord, ocrleftcount, message, annc_server, annc_sponsor), ok